package com.bobi.tfca.ui.mainnavigation.message.chatroom

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.bobi.tfca.network.ApiResponse
import com.bobi.tfca.network.api.MessageAPI
import com.bobi.tfca.network.response.ChatRoomResponse
import com.bobi.tfca.network.response.MessageResponse
import com.bobi.tfca.util.LogUtil
import com.bobi.tfca.viewmodel.PublicViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class ChatRoomFragmentVM : ViewModel() {

    val messages by lazy {
        MutableLiveData(ArrayList<MessageResponse>())
    }

    val title by lazy {
        MutableLiveData("")
    }

    /**
     * 查询聊天室的所有历史消息
     */
    fun getHistoryMessages(groupId: Int, publicViewModel: PublicViewModel?) {
        // 调用API查询聊天室所有历史消息
        var messageList: List<MessageResponse>? = arrayListOf()
        publicViewModel?.apply {
            request(MessageAPI::class.java).getChatRoomMessages(groupId).getResponse {
                it.collect{
                    when(it) {
                        is ApiResponse.Error -> {
                            LogUtil.e(it.errMsg)
                        }
                        ApiResponse.Loading -> LogUtil.e("Loading")
                        is ApiResponse.Success -> {
                            withContext(Dispatchers.Main) {
                                messageList = it.data?.data ?: arrayListOf()
                                messages.value = messageList as ArrayList<MessageResponse>
                            }
                        }
                    }
                }
            }
        }
    }
}